package com.qf.kafka.spring.boot.demo;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.kafka.support.serializer.JsonDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class MySimpleConsumer {



    private final static String TOPIC_NAME = "my-replicated-topic";
    private final static String CONSUMER_GROUP_NAME = "testGroup";

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094");
        // 消费分组名
        props.put(ConsumerConfig.GROUP_ID_CONFIG, CONSUMER_GROUP_NAME);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class.getName());




        //1.创建⼀个消费者的客户端
        KafkaConsumer<String, List<Map<String, String>>> consumer = new KafkaConsumer<>(props);
        //2. 消费者订阅主题列表
//        consumer.subscribe(Arrays.asList(TOPIC_NAME));
        consumer.assign(Arrays.asList(new TopicPartition(TOPIC_NAME, 0)));
        consumer.seek(new TopicPartition(TOPIC_NAME, 0), 2);
        while (true) {
            /*
             * 3.poll() API 是拉取消息的⻓轮询
             */
            ConsumerRecords<String, List<Map<String, String>>> records = consumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, List<Map<String, String>>> record : records) {
                List<Map<String, String>> value = record.value();
                //4.打印消息
                System.out.printf("收到消息：partition = %d,offset = %d, key = %s, value = %s%n", record.partition(), record.offset(), record.key(), record.value());
            }
            if (records.count() > 0) {//有消息
                // ⼿动同步提交offset，当前线程会阻塞直到offset提交成功
                // ⼀般使⽤同步提交，因为提交之后⼀般也没有什么逻辑代码了
                consumer.commitSync();//=======阻塞=== 提交成功
            }
            break;
        }
    }
}

